<?php
require_once '../config/database.php';
require_once '../utils/Database.php';
require_once '../utils/Response.php';

$db = new Database();

// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 引入认证函数
require_once 'admin_auth.php';

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

// 检查管理员权限
function requirePermission($permission) {
    $admin = getCurrentAdmin();
    if (!$admin) {
        Response::authError('请先登录');
    }
    
    if (!in_array($permission, $admin['permissions'])) {
        Response::error('权限不足');
    }
    
    return $admin;
}

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'roles':
                // 获取角色列表
                requirePermission('roles.view');
                
                $roles = $db->fetchAll("
                    SELECT r.*, 
                           (SELECT COUNT(*) FROM admin_users WHERE role_id = r.id) as user_count
                    FROM admin_roles r 
                    ORDER BY r.is_system DESC, r.created_at ASC
                ");
                
                // 解析权限JSON
                foreach ($roles as &$role) {
                    $role['permissions'] = json_decode($role['permissions'] ?? '[]', true);
                }
                
                Response::success($roles, '获取成功');
                break;
                
            case 'permissions':
                // 获取权限列表
                requirePermission('roles.view');
                
                $permissions = $db->fetchAll("
                    SELECT * FROM admin_permissions 
                    ORDER BY module, action
                ");
                
                // 按模块分组
                $groupedPermissions = [];
                foreach ($permissions as $permission) {
                    $module = $permission['module'] ?? 'other';
                    if (!isset($groupedPermissions[$module])) {
                        $groupedPermissions[$module] = [];
                    }
                    $groupedPermissions[$module][] = $permission;
                }
                
                Response::success($groupedPermissions, '获取成功');
                break;
                
            case 'admins':
                // 获取管理员列表
                requirePermission('admin.view');
                
                $page = (int)($_GET['page'] ?? 1);
                $limit = (int)($_GET['limit'] ?? 20);
                $search = $_GET['search'] ?? '';
                
                $offset = ($page - 1) * $limit;
                
                $whereClause = '';
                $params = [];
                
                if ($search) {
                    $whereClause = "WHERE a.username LIKE ? OR a.real_name LIKE ? OR a.email LIKE ?";
                    $searchTerm = "%{$search}%";
                    $params = [$searchTerm, $searchTerm, $searchTerm];
                }
                
                // 获取总数
                $totalResult = $db->fetchOne("
                    SELECT COUNT(*) as total 
                    FROM admin_users a 
                    $whereClause
                ", $params);
                $total = $totalResult['total'];
                
                // 获取列表
                $admins = $db->fetchAll("
                    SELECT a.id, a.username, a.real_name, a.email, a.phone, a.avatar,
                           a.status, a.last_login_time, a.login_count, a.created_at,
                           r.name as role_name, r.display_name as role_display_name
                    FROM admin_users a
                    LEFT JOIN admin_roles r ON a.role_id = r.id
                    $whereClause
                    ORDER BY a.created_at DESC
                    LIMIT $limit OFFSET $offset
                ", $params);
                
                Response::success([
                    'data' => $admins,
                    'total' => $total,
                    'page' => $page,
                    'limit' => $limit
                ], '获取成功');
                break;
                
            case 'admin_detail':
                // 获取管理员详情
                requirePermission('admin.view');
                
                $adminId = (int)($_GET['id'] ?? 0);
                if (!$adminId) {
                    Response::error('缺少管理员ID');
                }
                
                $admin = $db->fetchOne("
                    SELECT a.*, r.name as role_name, r.display_name as role_display_name, r.permissions
                    FROM admin_users a
                    LEFT JOIN admin_roles r ON a.role_id = r.id
                    WHERE a.id = ?
                ", [$adminId]);
                
                if (!$admin) {
                    Response::error('管理员不存在');
                }
                
                // 移除密码字段
                unset($admin['password']);
                $admin['permissions'] = json_decode($admin['permissions'] ?? '[]', true);
                
                Response::success($admin, '获取成功');
                break;
                
            case 'login_logs':
                // 获取登录日志
                requirePermission('logs.view');
                
                $page = (int)($_GET['page'] ?? 1);
                $limit = (int)($_GET['limit'] ?? 50);
                $adminId = $_GET['admin_id'] ?? null;
                
                $offset = ($page - 1) * $limit;
                
                $whereClause = '';
                $params = [];
                
                if ($adminId) {
                    $whereClause = 'WHERE admin_id = ?';
                    $params = [$adminId];
                }
                
                $logs = $db->fetchAll("
                    SELECT * FROM admin_login_logs 
                    $whereClause
                    ORDER BY created_at DESC 
                    LIMIT $limit OFFSET $offset
                ", $params);
                
                Response::success($logs, '获取成功');
                break;
                
            case 'operation_logs':
                // 获取操作日志
                requirePermission('logs.view');
                
                $page = (int)($_GET['page'] ?? 1);
                $limit = (int)($_GET['limit'] ?? 50);
                $adminId = $_GET['admin_id'] ?? null;
                $module = $_GET['module'] ?? null;
                
                $offset = ($page - 1) * $limit;
                
                $whereConditions = [];
                $params = [];
                
                if ($adminId) {
                    $whereConditions[] = 'admin_id = ?';
                    $params[] = $adminId;
                }
                
                if ($module) {
                    $whereConditions[] = 'module = ?';
                    $params[] = $module;
                }
                
                $whereClause = '';
                if (!empty($whereConditions)) {
                    $whereClause = 'WHERE ' . implode(' AND ', $whereConditions);
                }
                
                $logs = $db->fetchAll("
                    SELECT * FROM admin_operation_logs 
                    $whereClause
                    ORDER BY created_at DESC 
                    LIMIT $limit OFFSET $offset
                ", $params);
                
                Response::success($logs, '获取成功');
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'POST':
        switch ($action) {
            case 'create_role':
                // 创建角色
                $admin = requirePermission('roles.edit');
                
                if (!isset($input['name']) || !isset($input['display_name'])) {
                    Response::error('角色名称不能为空');
                }
                
                $name = trim($input['name']);
                $displayName = trim($input['display_name']);
                $description = trim($input['description'] ?? '');
                $permissions = $input['permissions'] ?? [];
                
                // 检查角色名是否已存在
                $existingRole = $db->fetchOne("SELECT id FROM admin_roles WHERE name = ?", [$name]);
                if ($existingRole) {
                    Response::error('角色名称已存在');
                }
                
                $roleId = $db->insert('admin_roles', [
                    'name' => $name,
                    'display_name' => $displayName,
                    'description' => $description,
                    'permissions' => json_encode($permissions),
                    'is_system' => 0,
                    'status' => 'active'
                ]);
                
                if ($roleId) {
                    logOperation($admin['id'], $admin['username'], 'create_role', 'roles', "创建角色: {$displayName}", $input);
                    Response::success(['id' => $roleId], '创建成功');
                } else {
                    Response::error('创建失败');
                }
                break;
                
            case 'create_admin':
                // 创建管理员
                $admin = requirePermission('admin.edit');
                
                if (!isset($input['username']) || !isset($input['password']) || !isset($input['role_id'])) {
                    Response::error('用户名、密码和角色不能为空');
                }
                
                $username = trim($input['username']);
                $password = $input['password'];
                $realName = trim($input['real_name'] ?? '');
                $email = trim($input['email'] ?? '');
                $phone = trim($input['phone'] ?? '');
                $roleId = (int)$input['role_id'];
                
                // 验证用户名格式
                if (!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) {
                    Response::error('用户名只能包含字母、数字和下划线，长度3-20位');
                }
                
                // 验证密码强度
                if (strlen($password) < 6) {
                    Response::error('密码长度不能少于6位');
                }
                
                // 检查用户名是否已存在
                $existingUser = $db->fetchOne("SELECT id FROM admin_users WHERE username = ?", [$username]);
                if ($existingUser) {
                    Response::error('用户名已存在');
                }
                
                // 检查邮箱是否已存在
                if ($email) {
                    $existingEmail = $db->fetchOne("SELECT id FROM admin_users WHERE email = ?", [$email]);
                    if ($existingEmail) {
                        Response::error('邮箱已存在');
                    }
                }
                
                // 检查角色是否存在
                $role = $db->fetchOne("SELECT id FROM admin_roles WHERE id = ? AND status = 'active'", [$roleId]);
                if (!$role) {
                    Response::error('角色不存在或已禁用');
                }
                
                $passwordHash = password_hash($password, PASSWORD_DEFAULT);
                
                $adminId = $db->insert('admin_users', [
                    'username' => $username,
                    'password' => $passwordHash,
                    'real_name' => $realName,
                    'email' => $email,
                    'phone' => $phone,
                    'role_id' => $roleId,
                    'status' => 'active'
                ]);
                
                if ($adminId) {
                    logOperation($admin['id'], $admin['username'], 'create_admin', 'admin', "创建管理员: {$username}", [
                        'username' => $username,
                        'real_name' => $realName,
                        'role_id' => $roleId
                    ]);
                    Response::success(['id' => $adminId], '创建成功');
                } else {
                    Response::error('创建失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'PUT':
        switch ($action) {
            case 'update_role':
                // 更新角色
                $admin = requirePermission('roles.edit');
                
                if (!isset($input['id'])) {
                    Response::error('缺少角色ID');
                }
                
                $roleId = (int)$input['id'];
                $displayName = trim($input['display_name'] ?? '');
                $description = trim($input['description'] ?? '');
                $permissions = $input['permissions'] ?? [];
                
                // 检查角色是否存在
                $role = $db->fetchOne("SELECT * FROM admin_roles WHERE id = ?", [$roleId]);
                if (!$role) {
                    Response::error('角色不存在');
                }
                
                // 系统角色不允许修改某些属性
                $updateData = [
                    'description' => $description,
                    'permissions' => json_encode($permissions),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
                
                if (!$role['is_system']) {
                    $updateData['display_name'] = $displayName;
                }
                
                $result = $db->update('admin_roles', $updateData, 'id = :id', ['id' => $roleId]);
                
                if ($result) {
                    logOperation($admin['id'], $admin['username'], 'update_role', 'roles', "更新角色: {$role['display_name']}", $input);
                    Response::success(['id' => $roleId], '更新成功');
                } else {
                    Response::error('更新失败');
                }
                break;
                
            case 'update_admin':
                // 更新管理员
                $admin = requirePermission('admin.edit');
                
                if (!isset($input['id'])) {
                    Response::error('缺少管理员ID');
                }
                
                $adminId = (int)$input['id'];
                $realName = trim($input['real_name'] ?? '');
                $email = trim($input['email'] ?? '');
                $phone = trim($input['phone'] ?? '');
                $roleId = (int)($input['role_id'] ?? 0);
                $status = $input['status'] ?? 'active';
                
                // 检查管理员是否存在
                $targetAdmin = $db->fetchOne("SELECT * FROM admin_users WHERE id = ?", [$adminId]);
                if (!$targetAdmin) {
                    Response::error('管理员不存在');
                }
                
                // 不能修改自己的状态和角色
                if ($adminId == $admin['id'] && ($status !== $targetAdmin['status'] || $roleId !== $targetAdmin['role_id'])) {
                    Response::error('不能修改自己的状态和角色');
                }
                
                $updateData = [
                    'real_name' => $realName,
                    'email' => $email,
                    'phone' => $phone,
                    'updated_at' => date('Y-m-d H:i:s')
                ];
                
                if ($roleId > 0) {
                    $updateData['role_id'] = $roleId;
                }
                
                if (in_array($status, ['active', 'inactive', 'banned'])) {
                    $updateData['status'] = $status;
                }
                
                $result = $db->update('admin_users', $updateData, 'id = :id', ['id' => $adminId]);
                
                if ($result) {
                    logOperation($admin['id'], $admin['username'], 'update_admin', 'admin', "更新管理员: {$targetAdmin['username']}", $input);
                    Response::success(['id' => $adminId], '更新成功');
                } else {
                    Response::error('更新失败');
                }
                break;
                
            case 'reset_password':
                // 重置密码
                $admin = requirePermission('admin.edit');
                
                if (!isset($input['id']) || !isset($input['new_password'])) {
                    Response::error('缺少必要参数');
                }
                
                $adminId = (int)$input['id'];
                $newPassword = $input['new_password'];
                
                if (strlen($newPassword) < 6) {
                    Response::error('密码长度不能少于6位');
                }
                
                // 检查管理员是否存在
                $targetAdmin = $db->fetchOne("SELECT username FROM admin_users WHERE id = ?", [$adminId]);
                if (!$targetAdmin) {
                    Response::error('管理员不存在');
                }
                
                $passwordHash = password_hash($newPassword, PASSWORD_DEFAULT);
                
                $result = $db->update('admin_users', [
                    'password' => $passwordHash,
                    'updated_at' => date('Y-m-d H:i:s')
                ], 'id = :id', ['id' => $adminId]);
                
                if ($result) {
                    logOperation($admin['id'], $admin['username'], 'reset_password', 'admin', "重置密码: {$targetAdmin['username']}");
                    Response::success(['id' => $adminId], '密码重置成功');
                } else {
                    Response::error('密码重置失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'DELETE':
        switch ($action) {
            case 'delete_role':
                // 删除角色
                $admin = requirePermission('roles.edit');
                
                $roleId = (int)($_GET['id'] ?? 0);
                if (!$roleId) {
                    Response::error('缺少角色ID');
                }
                
                // 检查角色是否存在
                $role = $db->fetchOne("SELECT * FROM admin_roles WHERE id = ?", [$roleId]);
                if (!$role) {
                    Response::error('角色不存在');
                }
                
                // 系统角色不能删除
                if ($role['is_system']) {
                    Response::error('系统角色不能删除');
                }
                
                // 检查是否有管理员在使用该角色
                $userCount = $db->fetchOne("SELECT COUNT(*) as count FROM admin_users WHERE role_id = ?", [$roleId]);
                if ($userCount['count'] > 0) {
                    Response::error('该角色下还有管理员，无法删除');
                }
                
                $result = $db->delete('admin_roles', 'id = ?', [$roleId]);
                
                if ($result) {
                    logOperation($admin['id'], $admin['username'], 'delete_role', 'roles', "删除角色: {$role['display_name']}");
                    Response::success(['id' => $roleId], '删除成功');
                } else {
                    Response::error('删除失败');
                }
                break;
                
            case 'delete_admin':
                // 删除管理员
                $admin = requirePermission('admin.edit');
                
                $adminId = (int)($_GET['id'] ?? 0);
                if (!$adminId) {
                    Response::error('缺少管理员ID');
                }
                
                // 不能删除自己
                if ($adminId == $admin['id']) {
                    Response::error('不能删除自己');
                }
                
                // 检查管理员是否存在
                $targetAdmin = $db->fetchOne("SELECT username FROM admin_users WHERE id = ?", [$adminId]);
                if (!$targetAdmin) {
                    Response::error('管理员不存在');
                }
                
                $result = $db->delete('admin_users', 'id = ?', [$adminId]);
                
                if ($result) {
                    logOperation($admin['id'], $admin['username'], 'delete_admin', 'admin', "删除管理员: {$targetAdmin['username']}");
                    Response::success(['id' => $adminId], '删除成功');
                } else {
                    Response::error('删除失败');
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}
?>